package test.NIO;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class NioServer {

    private static List<SocketChannel> clients = new ArrayList<SocketChannel>();


    public static void main(String[] args) {
        try {
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            serverSocketChannel.socket().bind(new InetSocketAddress(9099));
            serverSocketChannel.configureBlocking(false);

            //先启动线程
            new Thread(() -> {
                while (true) {

                    //遍历list将消息打印出来
                    for (SocketChannel client : clients) {
                        ByteBuffer wrap = ByteBuffer.wrap(new byte[1000]);
                        try {
                            client.read(wrap);
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                        System.out.println("接受到的数据："+ StandardCharsets.UTF_8.decode(wrap).toString());


                    }

                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }

                }

            }).start();


            //监听到消息，将socketChannel存入list
            while (true) {
                SocketChannel socketChannel = serverSocketChannel.accept();
                if (socketChannel != null) {
                    System.out.println("监听到了消息");
                    socketChannel.configureBlocking(false);
                    clients.add(socketChannel);
                }


            }



        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
